package com.test.converter;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter;

public class DateConverter extends DefaultTypeConverter {
	 private static final DateFormat[] ACCEPT_DATE_FORMATS = { 
		 new SimpleDateFormat("MM/dd/yyyy"), 
		 new SimpleDateFormat("dd/MM/yyyy"),  
         new SimpleDateFormat("yyyy-MM-dd"),  
         new SimpleDateFormat("yyyy/MM/dd") }; // date converter  

 @Override   
 public Object convertValue(Map context, Object value, Class toType) {   
     if (toType == Date.class) {  //while forwarding to server，convert String to Date
         Date date = null;   
         String dateString = null;   
         String[] params = (String[])value;   
         dateString = params[0];//get input string
         for (DateFormat format : ACCEPT_DATE_FORMATS) {   
             try {   
            	 System.out.println(dateString);
                 return format.parse(dateString);// iterate the type of date         
             } catch(Exception e) {   
                 continue;   
             }   
         }   
         return null;   
     }   
     else if (toType == String.class) {   //while output,convert Date to String
         Date date = (Date)value; 
         System.out.println(date);
         return new SimpleDateFormat("yyyy-MM-dd").format(date);//type yyyy-MM-dd   
         
     }          
     return null;   
 }  
}
